import { appConfig } from "../config/appConfig";
import { callLocalService } from "./localService";

interface CloudResult<T> {
  code: number;
  data: T;
  message?: string;
}

const SERVICE_NAME = "couplesService";

export async function callFunction<T>(
  name: string,
  data?: Record<string, unknown>
): Promise<T> {
  if (!appConfig.useCloud) {
    throw new Error("当前为本地模式，无法调用云函数");
  }
  const res = await wx.cloud.callFunction({
    name,
    data,
  });

  const result = res.result as CloudResult<T> | undefined;
  if (!result) {
    throw new Error("云函数返回为空");
  }

  if (result.code !== 200) {
    throw new Error(result.message || "云函数请求失败");
  }

  return result.data;
}

export function callService<T>(action: string, data?: Record<string, unknown>) {
  if (!appConfig.useCloud) {
    return Promise.resolve(callLocalService<T>(action, data || {}));
  }
  return callFunction<T>(SERVICE_NAME, { action, ...(data || {}) });
}
